﻿using System;
using System.Linq;
using System.Collections.Generic;
using NHibernate.Cfg;
using NHibernate;


namespace epicenter2010.NH.Querying.HQL
{
    /// <summary>
    /// Repository using HQL
    /// bstack @ 06/06/2010
    /// </summary>
    public class RepositoryUsingHQL
    {
        private readonly ISessionFactory c_sessionFactory;


        /// <summary>
        /// Ctor
        /// </summary>
		public RepositoryUsingHQL()
        {
            this.c_sessionFactory = (new Configuration()).Configure().BuildSessionFactory();
        }


        /// <summary>
        /// Get by Id
        /// </summary>
        /// <param name="id">Id</param>
        public IList<epicenter2010.NH.Querying.HQL.CustomerHQL> GetAll()
        {
            using (var _session = this.c_sessionFactory.OpenSession())
            {
                return _session.CreateQuery("from CustomerHQL c").List<epicenter2010.NH.Querying.HQL.CustomerHQL>();
            }
        }


        /// <summary>
        /// Get by Id
        /// </summary>
        /// <param name="id">Id</param>
		public epicenter2010.NH.Querying.HQL.CustomerHQL GetById(
            Guid id)
        {
			using (var _session = this.c_sessionFactory.OpenSession())
            {
				var _query = _session.CreateQuery("from CustomerHQL c where c.Id = :id");

				_query.SetString("id", id.ToString());
				
				return _query.UniqueResult<epicenter2010.NH.Querying.HQL.CustomerHQL>();
            }
        }


		 /// <summary>
        /// Save
        /// </summary>
        /// <param name="subject"></param>
        /// <returns></returns>
		public void Save(
			epicenter2010.NH.Querying.HQL.CustomerHQL subject)
		{
			using (var _session = this.c_sessionFactory.OpenSession())
			{
				using (var _transaction = _session.BeginTransaction())
				{
					try
					{
						_session.SaveOrUpdate(subject);
						_transaction.Commit();
					}
					catch (Exception)
					{
						_transaction.Rollback();
						throw;
					}
				}
			}
		}
    }
}
